<template>
    <popup :keepAlive="false" :maskClose="true" ref="mePopupRef" @close="closePopup">
        <div class="mePopup flex justify-center" v-loading="loading">
            <div class="left">
                <div class="defaultHead" :style="`background-image: url(${avatarUrl});`" v-loading="avatarLoading">
                    <!-- 上传 input 悬浮不显示提示文字 -->
                    <input type="file" accept="image/*" class="uploadInput" @input="uploadImg" ref="uploadInputRef" />
                </div>
                <div class="name flex items-center justify-center">
                    <input @blur="handleChangeName" :value="app.userInfo.name" class="nameInput" />
                </div>
                <div class="time flex justify-center">
                    {{ $t("me.joinedDays", { days: app.userInfo.data.playDay || 1 }) }}
                </div>
                <div class="from">
                    <div class="item flex items-center justify-between">
                        <div class="label">APM</div>
                        <div class="val">{{ app.userInfo.data.info.apm }}</div>
                    </div>
                    <div class="item flex items-center justify-between">
                        <div class="label">LPM</div>
                        <div class="val">{{ app.userInfo.data.info.lpm }}</div>
                    </div>
                    <div class="item flex items-center justify-between">
                        <div class="label">APL</div>
                        <div class="val">{{ app.userInfo.data.info.apl }}</div>
                    </div>
                    <div class="item flex items-center justify-between">
                        <div class="label">ADPM</div>
                        <div class="val">{{ app.userInfo.data.info.adpm }}</div>
                    </div>
                    <div class="item flex items-center justify-between">
                        <div class="label">VS</div>
                        <div class="val">{{ app.userInfo.data.info.vs }}</div>
                    </div>
                    <div class="item flex items-center justify-between">
                        <div class="label">GAME COUNT</div>
                        <div class="val">{{ app.userInfo.data.gameCount }}</div>
                    </div>
                </div>
                <button @click="showLogoutDialog" class="logoutButton">{{ $t("me.logout") }}</button>
            </div>
            <div class="right">
                <!-- 图表 -->
                <div class="ec" id="ecEl"></div>
                <div class="totalTitle flex items-center justify-center">
                    {{ $t("me.gameTotal") }}
                </div>
                <div class="totalItem flex items-center justify-between">
                    <div class="label">
                        <div class="p" style="background-color: #e658fe"></div>
                        SPEED
                    </div>
                    <div class="val">{{ app.userInfo.data.info.lpm }} LPM</div>
                </div>
                <div class="totalItem flex items-center justify-between">
                    <div class="label">
                        <div class="p" style="background-color: #ca402b"></div>
                        ATTACKS
                    </div>
                    <div class="val">{{ app.userInfo.data.info.apm }} APM</div>
                </div>
                <div class="totalItem flex items-center justify-between">
                    <div class="label">
                        <div class="p" style="background-color: #3f85ff"></div>
                        REN
                    </div>
                    <div class="val">{{ app.userInfo.data.total.maxCombo }}</div>
                </div>
                <div class="totalItem flex items-center justify-between">
                    <div class="label">
                        <div class="p" style="background-color: #ffe407"></div>
                        TETRIS
                    </div>
                    <div class="val">{{ infoFormat.tetris }}</div>
                </div>
                <div class="totalItem flex items-center justify-between">
                    <div class="label">
                        <div class="p" style="background-color: #d56c9b"></div>
                        T-SPIN
                    </div>
                    <div class="val">{{ infoFormat.tspin }}</div>
                </div>
                <div class="totalItem flex items-center justify-between">
                    <div class="label">
                        <div class="p" style="background-color: #1b9c35"></div>
                        BACK TO BACK
                    </div>
                    <div class="val">{{ infoFormat.btb }}</div>
                </div>
            </div>
            <el-dialog :title="$t('me.cancelLogout')" v-model="logoutDialogVisible" align-center :width="'400px'" :modal-append-to-body="true">
                <span>{{ $t("me.confirmLogout") }}</span>
                <template #footer>
                    <el-button @click="logoutDialogVisible = false" style="margin-right: 10px">{{ $t("me.cancel") }}</el-button>
                    <el-button type="primary" @click="confirmLogout" style="padding: 10px 20px; font-size: 16px">{{ $t("me.confirm") }}</el-button>
                </template>
            </el-dialog>
        </div>
    </popup>
</template>

<script lang="ts" setup>
import { ref, defineExpose, nextTick, defineEmits, computed } from "vue"
import fetch from "@/api/fetch.js"
import { upload } from "@/api/upload.js"
import useAppStore from "@/pinia"
import { ElMessageBox, ElDialog } from "element-plus"
const app = useAppStore()
const mePopupRef = ref()
const loading = ref(false)
const avatarLoading = ref(true)
import { baseUrl } from "@/utils/env"
import * as echarts from "echarts"
import { useWindowSize } from "@vueuse/core"
import { compressImg, loadingImage } from "@/utils/utils.ts"
const { height: WindowHeight, width: WindowWidth } = useWindowSize()
const min = Math.min(WindowHeight.value, WindowWidth.value)
const uploadInputRef = ref()

const avatarError = ref(false)
// 头像url
const avatarUrl = computed(() => {
    if (app.userInfo && app.userInfo.avatarUrl && !avatarError.value) {
        let url = app.userInfo.userType == "qq" ? app.userInfo.avatarUrl : baseUrl + app.userInfo.avatarUrl
        return url
    } else return baseUrl + "images/dh.png"
})

const infoFormat = ref({
    tetris: 0,
    tspin: 0,
    btb: 0,
})

const initEcharts = () => {
    let ecEl = echarts.init(document.getElementById("ecEl"))
    let info = app.userInfo.data.info
    let total = app.userInfo.data.total
    let gameCount = app.userInfo.data.gameCount
    let apm = info.apm > 60 ? 60 : info.apm
    let lpm = info.lpm > 48 ? 48 : info.lpm
    let btb = gameCount == 0 ? 0 : parseFloat((total.btb / gameCount).toFixed(2))
    infoFormat.value.btb = btb
    btb = btb > 6 ? 6 : btb
    let tspin = gameCount == 0 ? 0 : parseFloat((total.tspin / gameCount).toFixed(2))
    infoFormat.value.tspin = tspin
    tspin = tspin > 6 ? 6 : tspin
    let ren = total.maxCombo > 6 ? 6 : total.maxCombo
    let tetris = gameCount == 0 ? 0 : parseFloat(((total.tetris + total.btbTetris) / gameCount).toFixed(2))
    infoFormat.value.tetris = tetris
    tetris = tetris > 6 ? 6 : tetris
    let value = [apm, btb, tspin, ren, tetris, lpm]
    console.log("value", value)
    let option = {
        color: ["rgba(255, 255, 255, .7)"],
        radar: {
            shape: "circle",
            tooltip: {
                trigger: "item",
            },
            indicator: [
                { name: "APM", max: 60 },
                { name: "BTB", max: 6 },
                { name: "Tspin", max: 6 },
                { name: "Ren", max: 6 },
                { name: "Tetris", max: 6 },
                { name: "LPM", max: 48 },
            ],
            axisName: {
                color: "#bbb",
                fontSize: (min / 100) * 2, // 2vmin
            },
        },
        series: [
            {
                type: "radar",
                data: [
                    {
                        value,
                        areaStyle: {
                            color: "rgba(255, 255, 255, .5)",
                        },
                        // label: {
                        //     show: true,
                        //     formatter: function (params) {
                        //         return params.value;
                        //     }
                        // }
                    },
                ],
            },
        ],
    }
    ecEl.setOption(option)
}

const uploadImg = (e) => {
    let target = uploadInputRef.value
    let file = target.files[0]
    if (file) {
        compressImg(file)
            .then((formData) => {
                upload(formData, {
                    action: "avatar",
                    userId: app.userInfo.userId,
                })
                    .then((res) => {
                        console.log("uploadImg success res", res)
                        loading.value = true
                        // 上传头像后更新userInfo
                        fetch("getUserInfo", { userId: app.userInfo.userId })
                            .then((res) => {
                                loadingImage(baseUrl + res.avatarUrl)
                                    .then(() => (avatarError.value = false))
                                    .catch(() => (avatarError.value = true))
                                    .finally(() => (avatarLoading.value = false))
                                app.updateUserInfo(res)
                                app.showTopMessage("Avatar upload success", "success")
                            })
                            .finally(() => {
                                loading.value = false
                            })
                    })
                    .catch((err) => {
                        console.log("uploadImg error err", err)
                        app.showTopMessage(err.msg || "uploadImg error", "error")
                    })
            })
            .catch((err) => {
                console.log("compress err", err)
            })
    } else console.log("未选择上传文件")
}

const handleChangeName = (e) => {
    let name = e.target.value
    fetch("updateUserName", { userId: app.userInfo.userId, name }).then(() => {
        app.userInfo.name = name
        app.showTopMessage("Nickname upload success", "success")
    })
}

const show = () => {
    avatarError.value = false
    mePopupRef.value.show()
    loading.value = true
    console.log('app.userInfo',app.userInfo)
    fetch("getUserInfo", { userId: app.userInfo.userId })
        .then((res: any) => {
            let url = res.userType == "qq" ? res.avatarUrl : baseUrl + res.avatarUrl // qq登录用户直接使用avatarUrl 不拼接baseUrl
            loadingImage(url)
                .catch(() => (avatarError.value = true))
                .finally(() => (avatarLoading.value = false))
            app.updateUserInfo(res)
            setTimeout(() => {
                initEcharts()
            }, 200)
        })
        .catch((err: any) => {
            console.log("getUserInfo err", err)
            app.showMessage(err.msg || "网络异常 请刷新重试")
            hide()
        })
        .finally(() => {
            loading.value = false
        })
}

const hide = () => {
    closePopup()
    mePopupRef.value.closePopup()
}

const closePopup = () => {}

const logoutDialogVisible = ref(false)

const showLogoutDialog = () => {
    logoutDialogVisible.value = true
}

const confirmLogout = () => {
    hide()
    logoutDialogVisible.value = false
    setTimeout(() => {
        app.logout()
    }, 1000)
}

defineExpose({
    show,
    hide,
})
</script>

<style lang="scss" scoped>
.mePopup {
    border-radius: 1vmin;
    background-image: linear-gradient(70deg, rgb(9, 32, 63, 0.95) 0%, rgba(28, 50, 83, 0.95) 100%);
    padding: 2vmin 6vmin;
    box-sizing: border-box;
    height: auto;

    .left {
        width: 32vmin;
        height: auto;

        .defaultHead {
            width: 32vmin;
            height: 32vmin;
            background-size: cover;
            background-repeat: no-repeat;
            background-position: 50% 50%;
            border-radius: 0.5vmin;
            cursor: pointer;

            .uploadInput {
                opacity: 0;
                width: 100%;
                height: 100%;
            }
        }

        .name {
            height: 5vmin;
            margin-top: 1vmin;
            font-weight: 600;
            font-size: 2.3vmin;
            border-bottom: 1px solid rgba(255, 255, 255, 0.2);
            box-shadow: 0 1.5vmin 8vmin 0.2vmin rgba(255, 255, 255, 0.1);
            transition: all 0.2s;
            border-radius: 1vmin;
            cursor: pointer;

            &:hover {
                opacity: 0.7;
            }

            .nameInput {
                width: 100%;
                height: 100%;
                text-align: center;
            }
        }

        .time {
            padding: 1.5vmin 0;
            font-size: 1.7vmin;
        }

        .from {
            background: rgba(28, 50, 83, 0.8);
            border-radius: 1vmin;
            box-shadow: inset 0 0 1vmin 1vmin rgba(255, 255, 255, 0.05);

            .item {
                min-width: 30vmin;
                padding: 1.5vmin 2.5vmin;
                border-bottom: 1px solid rgba(255, 255, 255, 0.1);
                transition: all 0.5s;
                cursor: pointer;

                .label {
                    color: #ddd;
                    font-size: 2.1vmin;
                    font-weight: 200;
                }

                .val {
                    color: #ccc;
                    font-weight: bolder;
                    text-shadow: 0.5vmin 0.5vmin 1vmin rgba(235, 90, 165, 0.5);
                    font-size: 2.6vmin;
                }

                &:hover {
                    opacity: 0.5;
                }
            }
        }

        .logoutButton {
            width: 100%;
            height: 8vmin;
            border-radius: 1vmin;
            color: #ddd;
            font-size: 2.8vmin;
            letter-spacing: 1vmin;
            background: rgb(88, 101, 242, 0.3);
            margin-top: 2.5vmin;
            cursor: pointer;
            transition: all 0.4s ease-in-out;

            &:hover {
                background: rgb(76, 90, 232, 5);
            }
        }
    }

    .right {
        margin-left: 6vmin;
        height: auto;

        .ec {
            width: 35vmin;
            height: 40vmin;
        }

        .totalTitle {
            background: linear-gradient(315deg, rgba(2, 29, 78, 0.681) 0%, rgba(2, 29, 78, 0.381) 60%);
            padding: 1.5vmin 0;
            width: 100%;
            border-radius: 999vw;
            letter-spacing: 0.5vmin;
            font-size: 1.8vmin;
            border-bottom: 1px solid rgba(255, 255, 255, 0.1);
            box-shadow: inset 0 0 1vmin 1vmin rgba(255, 255, 255, 0.03);
            margin-bottom: 1vmin;
        }

        .totalItem {
            font-size: 2vmin;
            padding: 2vmin 0;
            border-bottom: 1px solid rgba(255, 255, 255, 0.1);

            .label {
                color: #ddd;
                font-weight: 600;
                position: relative;

                // 左侧白色圆点
                .p {
                    content: "";
                    position: absolute;
                    width: 1vmin;
                    height: 1vmin;
                    background-color: #fff;
                    top: 50%;
                    left: -2vmin;
                    transform: translate(-50%, -50%);
                    border-radius: 50%;
                }
            }
        }
    }

    .title {
        color: #ddd;
        font-size: 7vmin;
        font-weight: 600;
        letter-spacing: 1vmin;
        font-family: Floane;
    }

    .input {
        width: 100%;
        height: 12vmin;
        box-shadow: inset 0 0 1vmin 1vmin rgba(0, 0, 0, 0.05);
        background-color: rgba(255, 255, 255, 0.01);
        margin-top: 2vmin;
        border-radius: 1vmin;
        border-bottom: 1px solid rgba(255, 255, 255, 0.1);

        input {
            width: 100%;
            height: 100%;
            padding-left: 2vmin;
            color: #aaa;
            font-size: 4vmin;
            letter-spacing: 0.1vmin;

            &::placeholder {
                color: rgb(170, 170, 170, 0.5);
            }
        }
    }

    .button {
        width: 100%;
        height: 10vmin;
        border-radius: 1vmin;
        color: #ddd;
        font-size: 3.5vmin;
        letter-spacing: 1vmin;
        background: rgb(88, 101, 242, 0.3);
        margin-top: 3vmin;
        cursor: pointer;
        transition: all 0.4s ease-in-out;

        &:hover {
            background: rgb(76, 90, 232, 5);
        }
    }

    .logoutButton {
        margin-top: 15px;
        padding: 8px 16px;
        background-color: #f44336;
        color: white;
        border: none;
        border-radius: 5px;
        cursor: pointer;
        transition: background-color 0.3s;

        &:hover {
            background-color: #d32f2f;
        }
    }
}
</style>
